package com.controller;

import com.dao.userMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.model.Person;
import com.model.User;
import com.validation.PersonValidator;
import org.devefx.validator.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class HomeController {
 private Logger logger = LoggerFactory.getLogger( HomeController.class );

    @Resource
    private userMapper userMapper;

    @RequestMapping("/say")
    @ResponseBody
    public Person say(String say) {
        Person person = new Person("侯栋栋", (short) 24 );
        logger.info( "日志记录info" );
        logger.debug( "日志记录debug" );
        logger.error( "日志记录error" );
        return person;
    }

    @RequestMapping("/want")
    public  String want(String want  , ModelMap model){
        model.put( "want" ,want);
        return  "want";
    }

    @RequestMapping("/users.json")
    @ResponseBody
    public User user(){
        return  userMapper.selectByPrimaryKey( 1 );
    }

    @Valid(value=PersonValidator.class)
    @RequestMapping("/addUser.json")
    @ResponseBody
    public User addUser(User user){
        int id = userMapper.insert( user );
        System.out.println(user.getId());
        return userMapper.selectByPrimaryKey( user.getId() ) ;
    }

    @RequestMapping("/page")
    public String  userPage(@RequestParam(defaultValue = "1") int pageNum , @RequestParam(defaultValue = "10") int pageSize ,ModelMap model){
        PageHelper.startPage( pageNum,pageSize );
        //紧跟着的第一个select方法会被分页
        List<User> userList = userMapper.selectList();//分页时，实际返回的结果list类型是Page<E>，如果想取出分页信息，需要强制转换为Page<E>
        PageInfo<User> pageInfo=new PageInfo<User>(userList);
        model.addAttribute("pageInfo", pageInfo);
        return  "userIndex";
    }

}
